package com.hzbc.faceattendance.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class UnionIdToOpenIdConverter {

    @Autowired
    private RestTemplate restTemplate;

    //    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
//    private static final String WECHAT_API = "https://api.weixin.qq.com/cgi-bin/user/info/batchget";
//    private static final String MINI_PROGRAM_API = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String WECHAT_ALLUSER_API = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=";
    private static final String WECHAT_USERINFO_API = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=";

    /**
     * 分页获取所有用户的OpenID
     */
    public List<String> getAllUserOpenIds(String accessToken) {
        List<String> openIds = new ArrayList<>();
        String nextOpenId = "";

        do {
            String url = WECHAT_ALLUSER_API + accessToken + "&next_openid=" + nextOpenId;

            // 使用RestTemplate发送GET请求
            Map<String, Object> response = restTemplate.getForObject(url, Map.class);

            // 检查错误
            if (response != null && response.get("errcode") != null) {
                System.err.println("获取用户列表失败: " + response);
                break;
            }

            // 解析OpenID列表
            Map<String, Object> data = (Map<String, Object>) response.get("data");
            if (data != null) {
                List<String> openIdArray = (List<String>) data.get("openid");
                openIds.addAll(openIdArray);
            }

            nextOpenId = (String) response.get("next_openid");
        } while (nextOpenId != null && !nextOpenId.isEmpty());

        return openIds;
    }

    /**
     * 批量获取用户信息并匹配UnionID
     */
    public String findOpenIdByUnionId(String accessToken, List<String> openIds, String targetUnionId) throws Exception {
        int batchSize = 100;
        String url = WECHAT_USERINFO_API + accessToken;

        for (int i = 0; i < openIds.size(); i += batchSize) {
            int end = Math.min(i + batchSize, openIds.size());
            List<String> batchOpenIds = openIds.subList(i, end);

            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            List<Map<String, String>> userList = new ArrayList<>();
            for (String openId : batchOpenIds) {
                Map<String, String> user = new HashMap<>();
                user.put("openid", openId);
                user.put("lang", "zh_CN");
                userList.add(user);
            }
            requestBody.put("user_list", userList);
            // 设置请求头为JSON格式
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
            System.out.println("请求参数：" + JSON.toJSONString(requestBody));
            // 使用RestTemplate发送POST请求
            Map<String, Object> response = restTemplate.postForObject(url, requestEntity, Map.class);
            System.out.println("响应参数：" + JSON.toJSONString(response));
            // 检查错误
            if (response.containsKey("errcode")) {
                System.err.println("批量获取用户信息失败: " + response);
                continue;
            }

            // 解析用户信息
            List<Map<String, Object>> userInfoList = (List<Map<String, Object>>) response.get("user_info_list");
            for (Map<String, Object> userInfo : userInfoList) {
                if ((Integer) userInfo.get("subscribe") != 1) {
                    continue;
                }

                String unionId = (String) userInfo.get("unionid");
                if (targetUnionId.equals(unionId)) {
                    return (String) userInfo.get("openid");
                }
            }

            Thread.sleep(200);
        }

        return null;
    }

//
//    private static String getUnionId(String appId, String secret, String code) throws Exception {
//        String urlStr = MINI_PROGRAM_API + "?appid=" + appId + "&secret=" + secret +
//                "&js_code=" + code + "&grant_type=authorization_code";
//
//        JSONObject response = sendGetRequest(urlStr);
//        return response.getString("unionid");
//    }
//
//    public static String getPublicAccountOpenId(String token, String unionid) throws Exception {
////        String requestBody = "{\"user_list\":[{\"unionid\":\"" + unionid + "\",\"lang\":\"zh_CN\"}]}";
////        unionid = "OPENID_1";
//        String requestBody = "{\"user_list\":[{\"openid\":\"" + unionid + "\",\"lang\":\"zh_CN\"}]}";
//
//        JSONObject response = sendPostRequest(WECHAT_API + "?access_token=" + token, requestBody);
//        System.out.println("响应参数："+response.toString());
//        if(response.containsKey("errcode")){
//            throw new Exception("获取openid失败："+ response.get("errcode") + response.getString("errmsg"));
//        }
//        JSONArray userInfoList = response.getJSONArray("user_info_list");
//
//        if (userInfoList.size() > 0) {
//            return userInfoList.getJSONObject(0).getString("openid");
//        }
//        return null;
//    }

//    public static String getAccessToken(String appId, String appSecret) throws Exception {
//        String requestUrl = TOKEN_URL + "&appid=" + appId + "&secret=" + appSecret;
//
//        HttpURLConnection connection = (HttpURLConnection) new URL(requestUrl).openConnection();
//        connection.setRequestMethod("GET");
//
//        int responseCode = connection.getResponseCode();
//        if (responseCode != 200) {
//            throw new RuntimeException("HTTP请求失败，状态码: " + responseCode);
//        }
//
//        BufferedReader in = new BufferedReader(
//                new InputStreamReader(connection.getInputStream()));
//        String inputLine;
//        StringBuilder response = new StringBuilder();
//
//        while ((inputLine = in.readLine()) != null) {
//            response.append(inputLine);
//        }
//        in.close();
//
//        // 解析JSON响应
//        String jsonResponse = response.toString();
//        int tokenStart = jsonResponse.indexOf("\"access_token\":\"") + 16;
//        int tokenEnd = jsonResponse.indexOf("\"", tokenStart);
//
//        if (tokenStart < 16 || tokenEnd < 0) {
//            throw new RuntimeException("无效的响应格式: " + jsonResponse);
//        }
//
//        return jsonResponse.substring(tokenStart, tokenEnd);
//    }
//
//    public static String getUserInfo(String token) throws Exception {
//        String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+token+"&unionid=oGzP0v-wBG5BATXU3F5zjUW9yT6U&lang=LANG";
//        HttpURLConnection connection = (HttpURLConnection) new URL(requestUrl).openConnection();
//        connection.setRequestMethod("GET");
//
//        int responseCode = connection.getResponseCode();
//        if (responseCode != 200) {
//            throw new RuntimeException("HTTP请求失败，状态码: " + responseCode);
//        }
//
//        BufferedReader in = new BufferedReader(
//                new InputStreamReader(connection.getInputStream()));
//        String inputLine;
//        StringBuilder response = new StringBuilder();
//
//        while ((inputLine = in.readLine()) != null) {
//            response.append(inputLine);
//        }
//        in.close();
//
//        // 解析JSON响应
//        String jsonResponse = response.toString();
//        System.out.println("获取到的用户信息: " + jsonResponse);
//        int tokenStart = jsonResponse.indexOf("\"access_token\":\"") + 16;
//        int tokenEnd = jsonResponse.indexOf("\"", tokenStart);
//
//        if (tokenStart < 16 || tokenEnd < 0) {
//            throw new RuntimeException("无效的响应格式: " + jsonResponse);
//        }
//
//        return jsonResponse.substring(tokenStart, tokenEnd);
//    }
//
//    private static JSONObject sendGetRequest(String urlStr) throws Exception {
//        URL url = new URL(urlStr);
//        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//        conn.setRequestMethod("GET");
//
//        return parseResponse(conn);
//    }
//
//    private static JSONObject sendPostRequest(String urlStr, String body) throws Exception {
//        URL url = new URL(urlStr);
//        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//        conn.setRequestMethod("POST");
//        conn.setDoOutput(true);
//        conn.getOutputStream().write(body.getBytes());
//
//        return parseResponse(conn);
//    }
//
//    private static JSONObject parseResponse(HttpURLConnection conn) throws Exception {
//        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//        String inputLine;
//        StringBuilder response = new StringBuilder();
//
//        while ((inputLine = in.readLine()) != null) {
//            response.append(inputLine);
//        }
//        in.close();
//
//        return JSON.parseObject(response.toString());
//    }

//    public static void main(String[] args) {
//        String miniProgramAppId = "wx8dad6b1612dbffd3";
//        String miniProgramSecret = "65edfad533285ce11012a6f12a54caf7";
//        String wechatAppId = "wx700f201b511fb649";
//        String wechatAppSecret = "b1a72895cf12a5eb8fa97b53f7b25242";
//        String wxCode = "USER_WX_LOGIN_CODE";
//        String TARGET_UNION_ID = "oGzP0v-wBG5BATXU3F5zjUW9yT6U";
//        String publicAccountToken = "95_2O2Q1FBpQxy8YC4P8_H7OWXqBx-cC0xpZ_kpVR2Tla7ZxRZSewKnEptyEHpSVVHu9WfIrfT66Ih0EG3zAa9bwrlvRhf9KvoXU-StiR4PdCbnBBpoF-pnn8s61N4VRNeAFAEAW";
//        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
//                + wechatAppId + "&secret=" + wechatAppSecret;
//        try {
////            String accessToken = getAccessToken(wechatAppId, wechatAppSecret);
////            publicAccountToken =accessToken;
////            System.out.println("获取到的AccessToken: " + accessToken);
//        } catch (Exception e) {
//            System.err.println("获取AccessToken失败: " + e.getMessage());
//            e.printStackTrace();
//        }
//        try {
//
//
//            // 2. 分页获取所有用户的OpenID列表
//            List<String> allOpenIds = getAllUserOpenIds(publicAccountToken);
//            if (allOpenIds.isEmpty()) {
//                System.out.println("公众号没有关注用户");
//                return;
//            }
//            System.out.println("获取到 " + allOpenIds.size() + " 个关注用户");
//            // 3. 分批获取用户详细信息
//            String matchedOpenId = findOpenIdByUnionId(publicAccountToken, allOpenIds, TARGET_UNION_ID);
//
//            if (matchedOpenId != null) {
//                System.out.println("匹配成功！UnionID: " + TARGET_UNION_ID + " 对应的OpenID: " + matchedOpenId);
//            } else {
//                System.out.println("未找到匹配的用户，可能该用户未关注公众号");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        //获取用户信息
////        try {
////            getUserInfo(publicAccountToken);
////        } catch (Exception e) {
////            throw new RuntimeException(e);
////        }
//        //unionid查open ID
////        try {
////            // 第一步：获取unionid
//////            String unionid = getUnionId(miniProgramAppId, miniProgramSecret, wxCode);
////            String unionid = "oGzP0v-wBG5BATXU3F5zjUW9yT6U";
////
////            // 第二步：通过unionid查询公众号openid
////            String openid = getPublicAccountOpenId(publicAccountToken, unionid);
////
////            System.out.println("公众号OpenID: " + openid);
////        } catch (Exception e) {
////            e.printStackTrace();
////        }
//    }
}
